<template>
  <div class="user-management-container">
    <!-- 顶部标题和按钮 -->
    <div class="header-section">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions">
        <a-button type="primary" @click="showAddUserModal">
          <template #icon>
            <PlusOutlined />
          </template>
          添加用户
        </a-button>
        <a-button @click="refreshData" style="margin-left: 10px">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </a-button>
      </div>
    </div>

    <!-- 搜索和过滤区域 -->
    <div class="filter-section">
      <a-input-search v-model:value="searchText" placeholder="搜索用户名、邮箱或手机号" class="search-input" allow-clear />
      <div class="filter-controls">
        <a-select v-model:value="selectedRole" placeholder="选择角色" style="width: 150px; margin-right: 10px" allow-clear>
          <a-select-option value="">全部角色</a-select-option>
          <a-select-option v-for="role in roleOptions" :key="role.id" :value="role.id">
            {{ role.name }}
          </a-select-option>
        </a-select>
        <a-button @click="resetFilters" style="margin-left: 10px">重置</a-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-section">
      <a-table :columns="columns" :data-source="filteredUsers" :pagination="pagination" :loading="loading"
        rowKey="userId" bordered size="middle">
        <template #emptyText>
          <a-empty :description="loading ? '加载中...' : '暂无数据'" />
        </template>
        <template #bodyCell="{ column, record }">
          <!-- 角色列特殊样式 -->
          <template v-if="column.key === 'roles'">
            <a-space>
              <a-tag v-for="roleId in record.roleIds" :key="roleId" :color="getRoleColor(roleId)">
                {{ getRoleName(roleId) }}
              </a-tag>
            </a-space>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="编辑">
                <a-button type="link" size="small" @click="editUser(record)">
                  <template #icon>
                    <EditOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="分配角色">
                <a-button type="link" size="small" @click="showRoleModal(record)">
                  <template #icon>
                    <UserAddOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="创建角色">
                <a-button type="primary" @click="showCreateRoleModal()">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="重置密码">
                <a-popconfirm title="确定重置为默认密码123456？" @confirm="resetToDefaultPassword(record.userId)">
                  <a-button type="link" danger size="small">
                    <template #icon>
                      <KeyOutlined />
                    </template>
                  </a-button>
                </a-popconfirm>
              </a-tooltip>
              <a-popconfirm title="确定删除该用户吗？" @confirm="handleDeleteUser(record.userId)">
                <a-tooltip title="删除">
                  <a-button type="link" danger size="small">
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <!-- 添加/编辑用户模态框 -->
    <a-modal v-model:open="modalVisible" :title="isEditing ? '编辑用户' : '添加用户'" width="700px" @ok="handleSubmit"
      @cancel="resetForm" :confirm-loading="submitting">
      <a-form ref="formRef" :model="form" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="24">
          <!-- 左侧表单字段 -->
          <a-col :span="12">
            <a-form-item label="用户名" name="username">
              <a-input v-model:value="form.username" placeholder="请输入用户名" />
            </a-form-item>

            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="form.email" placeholder="请输入邮箱" />
            </a-form-item>

            <a-form-item label="手机号" name="phone">
              <a-input v-model:value="form.phone" placeholder="请输入手机号" />
            </a-form-item>

            <a-form-item v-if="!isEditing" label="密码" name="password">
              <a-input-password v-model:value="form.password" placeholder="请输入密码" />
            </a-form-item>

            <a-form-item v-if="!isEditing" label="初始角色" name="roleIds">
              <a-select v-model:value="form.roleIds" mode="multiple" placeholder="请选择角色">
                <a-select-option v-for="role in roleOptions" :key="role.id" :value="role.id">
                  {{ role.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <!-- 右侧头像上传区域 -->
          <a-col :span="12">
            <a-form-item label="头像" :wrapper-col="{ span: 24 }">
              <div style="text-align: center;">
                <a-upload name="filePath" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
                  
                :before-upload="beforeAvatarUpload" :custom-request="handleAvatarUpload">
                  <template v-if="form.filePath">
                    <img :src="form.filePath" alt="头像"
                      style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px;" />
                  </template>
                  <template v-else>
                    <div>
                      <plus-outlined />
                      <div style="margin-top: 8px;">上传头像</div>
                    </div>
                  </template>
                </a-upload>
                <div v-if="form.filePath" style="margin-top: 8px;">
                  <a-button size="small" @click="form.filePath = ''">移除头像</a-button>
                </div>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <template #footer>
        <a-button @click="resetForm">取消</a-button>
        <a-button type="primary" @click="handleSubmit" :loading="submitting">确定</a-button>
      </template>
    </a-modal>
    <!-- 分配角色模态框 -->
    <a-modal v-model:open="roleModalVisible" title="分配角色" width="500px" @ok="handleRoleSubmit"
      @cancel="() => (roleModalVisible = false)" :confirm-loading="roleSubmitting">
      <a-select v-model:value="selectedRoles" mode="multiple" style="width: 100%" placeholder="请选择角色">
        <a-select-option v-for="role in roleOptions" :key="role.id" :value="role.id">
          {{ role.name }}
        </a-select-option>
      </a-select>
    </a-modal>

    <a-modal v-model:open="createRoleModalVisible" title="创建新角色" width="600px" @ok="handleCreateRole"
      @cancel="resetRoleForm" :confirm-loading="roleCreating">
      <a-form ref="roleFormRef" :model="roleForm" :rules="roleFormRules" :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }">
        <a-form-item label="角色名称" name="name" required>
          <a-input v-model:value="roleForm.name" placeholder="如：管理员" />
        </a-form-item>
        <a-form-item label="角色编码" name="code" required>
          <a-input v-model:value="roleForm.code" placeholder="如：admin" />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-textarea v-model:value="roleForm.description" placeholder="请输入角色描述信息" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import {
  PlusOutlined, EditOutlined, DeleteOutlined,
  UserAddOutlined, KeyOutlined, ReloadOutlined, UserOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { getAllUserRoles, findAllUsers, addUserToRole, deleteUser, getRoles, getUserById, updateUser, resetPassword } from '@/api/sysUserController.ts'
import { getRolePermissions, updateRole, addRoleToPermissions, selectAllRoles, createRole } from '@/api/sysRoleController'
import { register } from '@/api/loginController'
import { uploadPic } from '@/api/bizMediaFileController'
const baseUrl = import.meta.env.VITE_PIC_BASE_URL
// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const roleSubmitting = ref(false)
const searchText = ref('')
const selectedRole = ref('')
const modalVisible = ref(false)
const roleModalVisible = ref(false)
const isEditing = ref(false)
const formRef = ref<FormInstance>()
const selectedRoles = ref<number[]>([])
const selectedUser = ref<any>(null)

// 创建角色相关状态
const createRoleModalVisible = ref(false)
const roleCreating = ref(false)
const roleFormRef = ref<FormInstance>()

// 角色表单数据
const roleForm = reactive({
  name: '',
  code: '',
  description: ''
})


// 表单数据
const form = reactive({
  userId: null,
  username: '',
  email: '',
  phone: '',
  password: '',
  roleIds: [],
  filePath: ''
})

// 表单验证规则
const formRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位字符', trigger: 'blur' }
  ],
  roleIds: [{ required: false, message: '请选择角色', trigger: 'change' }]
}

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 20, message: '角色名称不超过20个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[a-z_]+$/, message: '只能包含小写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '描述不超过100个字符', trigger: 'blur' }
  ]
}

// 显示创建角色模态框
const showCreateRoleModal = () => {
  resetRoleForm()
  createRoleModalVisible.value = true
}

// 重置角色表单
const resetRoleForm = () => {
  roleFormRef.value?.resetFields()
  Object.assign(roleForm, {
    name: '',
    code: '',
    description: ''
  })
}


// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page
    pagination.pageSize = pageSize
  }
})

// 表格列配置
const columns = [

  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 60
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 80
  },
  {
    title: '头像',
    key: 'filePath',
    width: 100,
    customRender: ({ record }) => {
      return record.filePath
        ? h('img', {
          src: record.filePath,
          style: {
            width: '70px',
            height: '70px',
            borderRadius: '50%',
            objectFit: 'cover'
          }
        })
        : h('a-avatar', { icon: h(UserOutlined), size: 40 })
    },
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 180
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: '角色',
    key: 'roles',
    width: 150
  },

  {
    title: '注册时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 角色选项和用户数据
const roleOptions = ref<any[]>([])
const users = ref<any[]>([])
const userRoleMap = ref<Record<number, number[]>>({});
// 计算属性 - 过滤后的用户列表
const filteredUsers = computed(() => {

  return users.value.filter(user => {
    const keywordMatch = !searchText.value ||
      user.username.toLowerCase().includes(searchText.value.toLowerCase()) ||
      (user.email && user.email.toLowerCase().includes(searchText.value.toLowerCase())) ||
      (user.phone && user.phone.includes(searchText.value))

    const roleMatch = !selectedRole.value ||
      user.roleIds?.includes(parseInt(selectedRole.value))

    return keywordMatch && roleMatch
  })
})

// 获取角色名称
const getRoleName = (roleId: number) => {
  if (!roleOptions.value || !roleId) return '未知角色';

  const role = roleOptions.value.find(r => r.id === Number(roleId));
  return role?.name || `未知角色(${roleId})`;
};

// 获取角色颜色
const getRoleColor = (roleId: number) => {
  const colors: Record<number, string> = {
    1: 'red',     // 管理员
    2: 'blue',    // 战队队长
    3: 'green'    // 战队成语那
  }
  return colors[roleId] || 'default'
}

// 头像上传前校验
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('头像图片大小不能超过2MB!');
    return false;
  }
  return true;
};

// 自定义上传处理
const handleAvatarUpload = async ({ file }: { file: File }) => {
  try {
    loading.value = true;
    const { data } = await uploadPic({}, file);
    if (data?.code === 0 && data.data?.filePath) {
      // 直接使用后端返回的完整MinIO地址（假设后端已返回完整URL）
      // form.filePath = data.data.filePath;
      // 或者如果后端只返回相对路径：
      form.filePath = `${baseUrl}${data.data.filePath}`;
      message.success('头像上传成功');
    } else {
      message.error(data?.message || '头像上传失败');
    }
  } catch (error) {
    console.error('头像上传错误:', error);
    message.error('头像上传失败');
  } finally {
    loading.value = false;
  }
};

// 重置密码为123456
const resetToDefaultPassword = async (userId: number) => {
  try {
    const { data: result } = await resetPassword({ id: userId })
    if (result.code === 0) {
      message.success('已重置为默认密码 123456')
    } else {
      message.error(result.message || '操作失败')
    }
  } catch (error) {
    message.error('请求失败')
    console.error('重置密码错误:', error)
  }
}
// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    // 并行请求用户数据和角色映射
    const [usersRes, rolesRes] = await Promise.all([
      findAllUsers(),
      getAllUserRoles()
    ]);

    // 处理用户数据
    if (usersRes.data?.code === 0 && Array.isArray(usersRes.data.data)) {
      users.value = usersRes.data.data;
    } else {
      users.value = [];
      throw new Error(usersRes.data?.message || '获取用户列表失败');
    }

    // 处理角色映射
    if (rolesRes.data?.code === 0 && rolesRes.data.data) {
      userRoleMap.value = rolesRes.data.data;

      // 合并角色数据到用户列表
      users.value = users.value.map(user => ({
        ...user,
        filePath: user.filePath,
        roleIds: userRoleMap.value[user.userId] || []
      }));
      console.log('处理后数据:', users.value[0])
    } else {
      throw new Error(rolesRes.data?.message || '获取角色映射失败');
    }

    pagination.total = users.value.length;
  } catch (error) {
    message.error(error.message || '数据加载失败');
    console.error('加载错误:', error);
  } finally {
    loading.value = false;
  }
};




// 获取角色列表
const fetchRoles = async () => {
  try {
    const { data: response } = await selectAllRoles()
    if (response?.code === 0 && Array.isArray(response.data)) {
      roleOptions.value = response.data.map(role => ({
        id: role.id,
        name: role.name,
        code: role.code,
        description: role.description
      }))
    } else {
      message.error(response?.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表错误:', error)
    message.error('获取角色列表失败')
  }
};


// 提交创建角色
const handleCreateRole = async () => {
  try {
    // 验证表单
    await roleFormRef.value?.validate()

    roleCreating.value = true

    // 调用创建角色接口
    const { data: result } = await createRole({
      name: roleForm.name,
      code: roleForm.code,
      description: roleForm.description
    })

    if (result.code === 0) {
      message.success('角色创建成功')
      createRoleModalVisible.value = false
      await fetchRoles() // 刷新角色列表
    } else {
      message.error(result.message || '创建角色失败')
    }
  } catch (error) {
    console.error('创建角色错误:', error)
    message.error('创建角色失败，请重试')
  } finally {
    roleCreating.value = false
  }
}

// 显示添加用户模态框
const showAddUserModal = () => {
  isEditing.value = false
  resetForm()
  modalVisible.value = true
}

// 编辑用户
const editUser = async (record: any) => {
  isEditing.value = true
  selectedUser.value = record
  try {
    const { data: res } = await getUserById({ userId: record.userId })
    console.log("data:", res);
    Object.assign(form, {
      userId: res.data.userId,
      username: res.data.username,
      email: res.data.email,
      phone: res.data.phone,
      filePath: res.data.filePath
    })

    modalVisible.value = true
  } catch (error) {
    message.error('获取用户信息失败')
    console.error('编辑用户错误:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    if (isEditing.value) {
      // 编辑用户
      const payload = {
        userId: form.userId,
        username: form.username,
        email: form.email,
        phone: form.phone,
        filePath: form.filePath,
      }

      const { data: result } = await updateUser(payload)
      if (result.code === 0) {
        message.success('用户更新成功')
        modalVisible.value = false
        await fetchUsers()
      } else {
        message.error(result.message || '更新失败')
      }
    } else {
      // 添加用户
      const payload = {
        username: form.username,
        email: form.email,
        phone: form.phone,
        password: form.password
      }

      const { data: result } = await register(payload)
      console.log("result:", result);

      if (result.code === 0) {
        if (form.roleIds?.length > 0) {
          await addUserToRole({
            userId: result.userId,
            roleIds: form.roleIds
          })
        }

        message.success('用户创建成功')
        modalVisible.value = false
        await fetchUsers()
      } else {
        message.error(result.message || '创建失败')
      }
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    message.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}


// 显示分配角色模态框
const showRoleModal = async (record: any) => {
  selectedUser.value = record;
  try {
    // 直接从内存中获取已分配角色，不再请求接口
    selectedRoles.value = [...(userRoleMap.value[record.userId] || [])];
    roleModalVisible.value = true;
  } catch (error) {
    message.error('获取用户角色失败');
    console.error('获取用户角色错误:', error);
  }
};

// 提交角色分配
const handleRoleSubmit = async () => {
  if (!selectedUser.value) return;

  roleSubmitting.value = true;
  try {
    const { data: result } = await addUserToRole({
      userId: selectedUser.value.userId,
      roleIds: selectedRoles.value
    });

    if (result.code === 0) {
      // 更新本地角色映射
      userRoleMap.value[selectedUser.value.userId] = [...selectedRoles.value];

      // 更新用户列表中的角色显示
      const userIndex = users.value.findIndex(u => u.userId === selectedUser.value.userId);
      if (userIndex !== -1) {
        users.value[userIndex].roleIds = [...selectedRoles.value];
      }

      message.success('角色分配成功');
      roleModalVisible.value = false;
    } else {
      message.error(result.message || '角色分配失败');
    }
  } catch (error) {
    console.error('分配角色错误:', error);
    message.error('角色分配失败，请重试');
  } finally {
    roleSubmitting.value = false;
  }
};

// 删除用户
const handleDeleteUser = async (userId: number) => {
  try {
    const { data: result } = await deleteUser({ id: userId })
    if (result.code === 0) {
      message.success('用户删除成功')
      await fetchUsers()
    } else {
      message.error(result.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户错误:', error)
    message.error('删除失败，请重试')
  }
}


// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    userId: null,
    username: '',
    email: '',
    phone: '',
    password: '',
    roleIds: [],
    filePath: ''
  })
  modalVisible.value = false; 
  isEditing.value = false
}

// 重置筛选
const resetFilters = () => {
  searchText.value = ''
  selectedRole.value = ''
}

// 刷新数据
const refreshData = () => {
  fetchUsers()
  message.success('数据已刷新')
}

// 初始化
onMounted(async () => {
  await fetchRoles()
  await fetchUsers()
})
</script>

<style scoped>
/* 保持原有样式不变 */
.user-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.header-actions {
  display: flex;
  align-items: center;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.table-section {
  margin-top: 20px;
}

/* 表格行样式 */
:deep(.ant-table-row.admin-row) {
  background-color: #f6f9ff;
}

/* 操作按钮间距 */
:deep(.ant-space) {
  gap: 8px !important;
}

/* 表格滚动条样式 */
:deep(.ant-table-body) {
  scrollbar-width: thin;
  scrollbar-color: #d9d9d9 #f5f5f5;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  height: 8px;
  width: 8px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background-color: #d9d9d9;
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background-color: #f5f5f5;
}

/* 创建角色表单样式 */
.role-form-item {
  margin-bottom: 16px;
}

/* 模态框内容区域样式 */
:deep(.ant-modal-body) {
  padding: 24px;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.ant-upload-text {
  margin-top: 8px;
  color: #666;
}

:deep(.ant-table-cell) .ant-avatar {
  display: block !important;
}
</style>